package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.activities.BookDetailActivity;
import me.shurufa.bean.Book;
import me.shurufa.bean.TaBook;
import me.shurufa.bean.UserInfoEntity;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.TaBookListResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;

/**
 * 作者 : andy
 * 日期 : 16/3/8 17:50
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 他的书评一级界面
 */
public class TACommentFragment extends BaseFragment {

    @Bind(R.id.recycler_view)
    SuperRecyclerView mRecyclerView;

    private UserInfoEntity mUserInfo;
    private ListAdapter mAdapter;

    private ArrayList<TaBook> mDataList;
    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkUtils.isNetAvailable(getActivity())) {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                loadData(mPage);
            }
        }
    };

    public static TACommentFragment newInstance(UserInfoEntity userInfoEntity) {
        TACommentFragment fragment = new TACommentFragment();
        Bundle args = new Bundle();
        args.putSerializable(Constants.ARG_USER_INFO, userInfoEntity);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mUserInfo = (UserInfoEntity) getArguments().getSerializable(Constants.ARG_USER_INFO);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ta, container, false);
        ButterKnife.bind(this, view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.getRecyclerView().setHasFixedSize(true);
        mRecyclerView.setOnScrollListener(mOnScrollListener);

        mDataList = new ArrayList<>();
        mAdapter = new ListAdapter();
        HeaderAndFooterRecyclerViewAdapter headerAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAdapter);
        mRecyclerView.setAdapter(headerAndFooterRecyclerViewAdapter);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        refresh();
        return view;
    }

    public void refresh() {
        mPage = 1;
        loadData(mPage);
    }

    protected void loadData(final int page) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("page", page);
        params.addFormDataPart("user_id", mUserInfo.user_id);

        HttpRequest.post(API.GET_USER_BOOK_COMMENT_LIST, params, new HttpCallback<TaBookListResp>() {
            @Override
            public void onRespSuccess(TaBookListResp bookListResp) {
                try {
                    handleResponse(bookListResp, (page == 0 || page == 1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(TaBookListResp bookListResp) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
                refreshComplete();
            }
        });
    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(mRecyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }
    }

    /**
     * 处理返回结果
     * 1. 去重
     * @param bookListResp     data
     * @param isPullToRefresh  boolean
     */
    private void handleResponse(TaBookListResp bookListResp, boolean isPullToRefresh) {
        // 是否还有更多
        hasMore = !(bookListResp.data == null || Utils.isNullForList(bookListResp.data));

        // 1. 判空
        if (bookListResp.data == null || Utils.isNullForList(bookListResp.data)) {
            if (isPullToRefresh) {
                mRecyclerView.getEmptyView().setVisibility(View.VISIBLE);
            }
            return;
        }

        // 3. 添加进列表并刷新
        mAdapter.append(bookListResp.data);

        // 4. 页码自增
        mPage ++;

    }


    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView.getRecyclerView());
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    if (!NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        return;
                    }
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    class ListAdapter extends RecyclerView.Adapter<ListAdapter.TaDigestViewHolder> {

        @Override
        public TaDigestViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_ta_digest, viewGroup, false);
            return new TaDigestViewHolder(view);
        }

        @Override
        public void onBindViewHolder(TaDigestViewHolder holder, int position) {

            try {

                holder.header.setVisibility(position == 0 ? View.VISIBLE : View.GONE);

                TaBook book = mDataList.get(position);
                holder.tvBookTitle.setText(book.title);
                holder.tvCreateTime.setText(Utils.getFormatTime(book.created_at) + getString(R.string.book_comment_suffix));
                holder.tvContent.setText(book.content);
                Glide.with(getActivity())
                        .load(book.image)
                        .placeholder(R.drawable.ic_book_loading)
                        .error(R.drawable.ic_book_loading)
                        .into(holder.ivBookImg);

                bindListener(holder, position);
            } catch (Exception e) {
                e.printStackTrace();
                Utils.showToast(R.string.sys_err);
            }

        }

        private void bindListener(TaDigestViewHolder holder, int position) {
            final Book book = mDataList.get(position);
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), BookDetailActivity.class);
                    intent.putExtra(Constants.ARG_BOOK, book);
                    intent.putExtra(Constants.ARG_FROM_WHERE, Constants.TYPE_FROM_USER_CENTER_COMMENT);
                    intent.putExtra(Constants.ARG_USER_ID, String.valueOf(mUserInfo.user_id));
                    getActivity().startActivity(intent);
                }
            });
        }


        @Override
        public int getItemCount() {
            return mDataList == null ? 0 : mDataList.size();
        }

        public void append(List<TaBook> items) {
            if (Utils.isNullForList(items)) {
                return;
            }
            int pos = mDataList.size();
            mDataList.addAll(items);
            notifyItemRangeInserted(pos, items.size());
        }


        class TaDigestViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.book_img)
            ImageView ivBookImg;

            @Bind(R.id.book_title)
            TextView tvBookTitle;

            @Bind(R.id.create_time)
            TextView tvCreateTime;

            @Bind(R.id.book_content)
            TextView tvContent;

            @Bind(R.id.item_root)
            LinearLayout item;

            @Bind(R.id.header)
            View header;

            public TaDigestViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

    }
}
